﻿// Extensions Made Easy - Copyright 2012 by Jan Van der Haegen - All rights reserved, use for educational purposes only.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using ExtensionsMadeEasy.ClientAPI.Utilities.Base;
using ExtensionsMadeEasy.ClientAPI.Utilities.Extensions;
using Microsoft.LightSwitch.BaseServices.Notifications;
using Microsoft.LightSwitch.Runtime.Shell;

namespace ExtensionsMadeEasy.Navigation
{
    [Export(typeof(IRecentlyClosedScreenListener))]
    public class RecentlyClosedScreenListener : NotifyPropertyChangedBase, IRecentlyClosedScreenListener
    {
        private readonly string key;
        private readonly List<string> recentlyClosedScreens;

        public RecentlyClosedScreenListener()
        {
            this.key = "EME.RecentlyClosedScreenListener." + this.GetServiceProxy().CurrentUserViewModel.CurrentUserDisplayName;
            this.recentlyClosedScreens = this.GetServiceProxy().UserSettingsService.GetSetting<List<string>>(this.key);
         
            if (this.recentlyClosedScreens == null)
            {
                this.recentlyClosedScreens = new List<string>();
            }
            this.GetServiceProxy().UserSettingsService.Closing += new EventHandler<EventArgs>(UserSettingsService_Closing);
            this.GetServiceProxy().NotificationService.Subscribe(typeof(ScreenClosedNotification), OnScreenClosed);
        }

        void UserSettingsService_Closing(object sender, EventArgs e)
        {
            this.GetServiceProxy().UserSettingsService.SetSetting(this.key, this.recentlyClosedScreens);
        }

        public void OnScreenClosed(Notification n)
        {
            ScreenClosedNotification notification = n as ScreenClosedNotification;
            if (notification.Screen != null)
            {
                string displayName = notification.Screen.DisplayName;
                this.recentlyClosedScreens.Remove(displayName);
                this.recentlyClosedScreens.Insert(0, displayName);
                this.OnPropertyChanged(() => this.RecentlyClosedScreens);
            }
        }

        public List<string> RecentlyClosedScreens
        {
            get
            {
                return this.recentlyClosedScreens;
            }
        }
    }
}